package com.example.exception;


import com.example.common.result.Result;
import com.example.config.RedisCache;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@Slf4j
@RestControllerAdvice
//@ControllerAdvice(basePackages="com.example.controller")
public class GlobalExceptionHandler {

    @Autowired
    private RedisCache redisCache;

    @ExceptionHandler(ExpiredJwtException.class)
//    @ResponseBody//返回json串
    public Result JwtError(ExpiredJwtException e){
//        System.out.println("用户qingiqu 异常");
//        log.error(e.getCode() + " -- " + e.getMsg());
        return Result.error("token过期", "401");
    }

    @ExceptionHandler(CustomException.class)
//    @ResponseBody//返回json串
    public Result customError(CustomException e){
        log.error(e.getCode() + " -- " + e.getMsg());
//        System.out.println("用户qingiqu 异常");
        return Result.error(e.getMsg(), e.getCode());
    }

    //统一异常处理@ExceptionHandler,主要用于Exception
    @ExceptionHandler(Exception.class)
//    @ResponseBody//返回json串
    public Result error(Exception e){
        log.error("异常信息：",e);
//        redisCache.deleteObject("insertCoptc");
        return Result.error(e.getMessage(), "500");
    }

    /**
     * 处理JSR303参数校验异常信息
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handleVaildException(MethodArgumentNotValidException e){

        // 获取并组装JSR303参数校验失败异常信息
        StringBuffer stringBuffer = new StringBuffer();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach(item ->{
            String message = item.getDefaultMessage();
            String field = item.getField();
            stringBuffer.append(field + ":" + message + " ");
        });
        return Result.error(stringBuffer + "");
    }

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }
}
